package com.sts.common.utils;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Options;
import com.googlecode.aviator.runtime.type.AviatorFunction;
import com.sts.transform.function.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lsl
 * @since 2025年07月08日 19:36
 */
@Slf4j
public class FunctionUtil {

    private static boolean flag = false;
    private static final ReentrantLock LOCK = new ReentrantLock();

    public static void init() {
        if (!flag) {
            LOCK.lock();
            try {
                if (!flag) {
                    AviatorEvaluator.getInstance().useLRUExpressionCache(1000);
                    AviatorEvaluator.getInstance().setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL, true);

                    AviatorEvaluator.addFunction(new IDFunction());
                    AviatorEvaluator.addFunction(new RandCnNameFunction());
                    AviatorEvaluator.addFunction(new RandCnPhoneFunction());
                    AviatorEvaluator.addFunction(new RandDateFunction());
                    AviatorEvaluator.addFunction(new RandDecimalFunction());
                    AviatorEvaluator.addFunction(new RandEleFunction());
                    AviatorEvaluator.addFunction(new RandEmailFunction());
                    AviatorEvaluator.addFunction(new RandIntFunction());
                    AviatorEvaluator.addFunction(new RoundFunction());
                    AviatorEvaluator.addFunction(new RowGetFunction());
                    AviatorEvaluator.addFunction(new SeqEleFunction());
                    AviatorEvaluator.addFunction(new UUIDFunction());
                    AviatorEvaluator.addFunction(new SnowIDFunction());

                    flag = true;
                    log.info("Function Init Success");
                }
            } finally {
                LOCK.unlock();
            }
        }
    }

    public static void registryFunction(AviatorFunction function) {
        init();
        AviatorEvaluator.addFunction(function);
    }
}
